<?php
namespace control;
/*
*委外加工单跟踪类
*/

class outsourceProcessTrackClass extends adIndexClass
{
    private const page = 'outsourceProcessTrack';
    private const title = '委外加工单跟踪';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单据编号",
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'supplier'  => [
                        'name'  => "委外单位",
                        'width' => 150,
                    ],
                    'code'         => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 50,
                    ],
                    'process'          => [
                        'name'  => '工序',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '生产数量',
                        'width' => 100,
                    ],
                    'notIn'          => [
                        'name'  => '未入库数量',
                        'width' => 100,
                    ],
                    'planTime'          => [
                        'name'  => '计划交货日期',
                        'width' => 120,
                    ],
                    'lastDate'          => [
                        'name'  => '最后入库日期',
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "单据编号"   => text(array("name" => "orderNo")),
                    '委外单位' => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'where'=>"coid = '".self::$coid."' and outsource = '是'",'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                    "工序"   => text(array("name" => "process")),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['待入库','部分入库','已入库']]),
                    "计划交货日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),//证件编号
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "b.supplierId" => $this->post('supplierId'),
            "b.coid"=>self::$coid,
            "b.state"=>'已确认'
        );
        $and = match ($this->post('state')) {
            '待出库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from outsource_in_order_detail where sourceId = a.id)) = 0",
            '部分出库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from outsource_in_order_detail where sourceId = a.id)) > 0 and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from purchase_get_order_detail where sourceId = a.id)) < a.num",
            '已出库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from outsource_in_order_detail where sourceId = a.id)) = a.num",
            default=>'',
        };
        if ($this->post('createTime')) {
            //单据日期
            $and .=self::timeComparison($this->post('createTime'),field: 'b.recordDate');
        }
        if ($this->post('time')) {
            //单据日期
            $and .=self::timeComparison($this->post('time'),field: 'b.planTime');
        }
        if ($this->post('process')) {
            $and .= " and a.processId in (select id from process where name like '%".$this->post('process')."%') ";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.recordDate desc,b.orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "outsource_process_material as a join outsource_process as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,b.recordDate,b.orderNo,b.supplierId,b.planTime,c.code,c.name as materialName,c.model,c.unit",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //已入库数量
            $in_num = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from outsource_in_order_detail where sourceId = '$array[id]')",'sum'=>"num"));
            $state = '待入库';
            if ($array['num'] > $in_num && $in_num >0){
                $state = '部分入库';
            }elseif($in_num >= $array['num'] && $in_num >0){
                $state = '已入库';
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $row[] = supplierClass::getName($array['supplierId']);
                        break;
                    case "num":
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case "process":
                        $process = query('process', "id = '$array[processId]'", "name");
                        $row[] = $process['name'];
                        break;
                    case "notIn":
                        $row[] = $array['num']-$in_num;
                        break;
                    case "lastDate":
                        //最后入库日期
                        $last = find(array('table'=>'inventory_detail as a join inventory as b on a.orderId = b.id','field'=>"date(b.time) as lastDate",'single'=>"a.sourceId in (select id from outsource_in_order_detail where sourceId = '$array[id]') order by b.time desc"));
                        $row[] = isset($last['lastDate'])&&$state!='待入库'?$last['lastDate']:'';
                        break;
                    case "state":
                        $row[] = $state;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $numTotal = find([
            'table'  => "outsource_process_material as a join outsource_process as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        //已入库数量
        $in_num = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from outsource_in_order_detail where sourceId in (select a.id from outsource_process_material as a join outsource_process as b on a.orderId = b.id join material as c on c.id = a.materialId where 1=1 {$where}))",'sum'=>"num"));
        $total    = [
            'num'        => self::lostZero($numTotal['num'], 'numPrecision'),
            'notIn'        => self::lostZero($numTotal['num'] - $in_num, 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "outsource_process_material as a join outsource_process as b on a.orderId = b.id join material as c on c.id = a.materialId",
                    'field'=>"a.*,b.recordDate,b.orderNo,b.supplierId,b.planTime,c.code,c.name as materialName,c.model,c.unit",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by b.recordDate desc,b.orderNo desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $process = query('process', "id = '$array[processId]'", "name");
                //已入库数量
                $in_num = find(array(
                    'table'=>'inventory_detail',
                    'where'=>"sourceId in (select id from outsource_in_order_detail where sourceId = '$array[id]')",
                    'sum'=>"num"
                ));
                $state = '待入库';
                if ($array['num'] > $in_num && $in_num >0){
                    $state = '部分入库';
                }elseif($in_num >= $array['num'] && $in_num >0){
                    $state = '已入库';
                }
                //最后入库日期
                $last = find(array(
                    'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field'=>"date(b.time) as lastDate",
                    'single'=>"a.sourceId in (select id from outsource_in_order_detail where sourceId = '$array[id]') order by b.time desc"
                ));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '委外单位'=>supplierClass::getName($array['supplierId']),
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '工序'=>$process['name'],
                            '生产数量'=>self::lostZero($array['num'],'numPrecision'),
                            '未入库数量'=>self::lostZero($array['num']-$in_num,'numPrecision'),
                            '计划交货日期'=>$array['planTime'],
                            '最后入库日期'=>isset($last['lastDate'])&&$state!='待入库'?$last['lastDate']:'',
                            '状态'=>$state,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了委外加工单跟踪";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "委外加工单跟踪.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'委外单位',
                    'aliasName'=>'委外单位',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'工序',
                    'aliasName'=>'工序',
                ],
                [
                    'columnName'=>'生产数量',
                    'aliasName'=>'生产数量',
                ],
                [
                    'columnName'=>'未入库数量',
                    'aliasName'=>'未入库数量',
                ],
                [
                    'columnName'=>'计划交货日期',
                    'aliasName'=>'计划交货日期',
                ],
                [
                    'columnName'=>'最后入库日期',
                    'aliasName'=>'最后入库日期',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}

